<template>
  <div class="common-layout">
    <div style="font-size: 26px; margin-bottom: 10px">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }"
          ><span style="color: #c2c6cc">首页</span></el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/thematic-education' }">
          <span style="color: #c2c6cc">通用教育</span></el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <div class="layout-container">
      <div class="left">
        <form class="form" @submit.prevent="submitForm">
          <p>培训信息</p>
          <div class="group">
            <input
              required="true"
              class="main-input"
              type="text"
              v-model="planObj.planName"
            />
            <span class="highlight-span"></span>
            <label class="lebal-email">方案名</label>
          </div>
          <div class="container-1">
            <div class="group">
              <input
                required="true"
                class="main-input"
                type="text"
                v-model="planObj.totalSecond"
              />
              <span class="highlight-span"></span>
              <label class="lebal-email">学时(分钟)</label>
            </div>
          </div>
          <button class="submit" :disabled="userList.length === 0">提交</button>
        </form>
      </div>
      <div class="center">
        <h2>参与培训人员</h2>
        <div v-if="!isDefense">
          <el-button type="primary" @click="sign">开始签到</el-button>
        </div>
        <div v-else class="content">
          <Loading :text="loadingText"></Loading>
        </div>
        <div class="participants">
          <div
            class="participant"
            v-for="(item, index) in userList"
            :key="index"
            :style="{ backgroundColor: item.leave ? '#3a3a4b ' : 'green' }"
          >
            {{ item.userName }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onBeforeUnmount, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { openDefenseApi, closeDefenseApi } from "@renderer/api/face";
import { useStoreTemplate } from "@renderer/store/modules/template";
import { ArrowRight } from "@element-plus/icons-vue";
import MessageType from "@renderer/utils/message";
import Loading from "@renderer/components/loading/loading.vue";
import { createGeneralPlanApi } from "@renderer/api/face";
import { Plan } from "@renderer/bean/plan";
import { User } from "@renderer/bean/user";
import { ElMessage, ElMessageBox } from "element-plus";
import { status, data, send, open } from "@renderer/utils/websocket";
const router = useRouter();
const store = useStoreTemplate();
const planObj = ref<Plan>({
  planName: "",
  totalSecond: 10,
});

// 布防状态
const isDefense = ref(false);
// 向Loading组件传递text参数
const loadingText = ref("正在识别中,请抬头看向屏幕");

//已签到人员列表
const userList = ref<User[]>([]);
//记录签到人员工种
const jobTypeList = ref([]);
//签到状态
const signState = ref(false);
//监听store的值变化
watch(store, (newVal) => {
  if (newVal.messages.serviceType === MessageType.FACE_MESSAGE) {
    // startCountdown();
    const data = newVal.messages.data;
    //把data对象添加到userList中，如果data.userName已经存在，则不添加
    if (
      !userList.value.some((item) => {
        return item.userName === data.userName;
      })
    ) {
       // 如果用户不存在，添加到列表中
       data.isWatching = true;
      data.watchTime = 0;
      userList.value.push(data);
      console.log("userList", userList.value);
    }
    //记录签到人员工种
    if (!jobTypeList.value.includes(data.jobTypeName)) {
      jobTypeList.value.push(data.jobTypeName);
    }
  }
});

function sign() {
  isDefense.value = !isDefense.value;
  openDefenseApi(); //进入签到状态
  //推送考试状态
  const message = {
    serviceType: MessageType.TRAIN_STATE,
    content: JSON.stringify({ trainState: true }),
  };
  send(JSON.stringify(message));
}
//提交培训结果
async function submitForm() {
  const { code, data, message } = await createGeneralPlanApi({
    planName: planObj.value.planName,
    totalSecond: planObj.value.totalSecond,
    userIds: userList.value.map((item) => item.userId).join(","),
  });
  if (code == 2000) {
    //推送结束消息
    const message = {
      serviceType: MessageType.TRAIN_STATE,
      content: JSON.stringify({ trainState: false }),
    };
    send(JSON.stringify(message));
    ElMessageBox.alert("记录学时成功", "记录结果", {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: "确定",
      callback: (action: Action) => {
        closeDefenseApi();
        router.push("/");
      },
    });
  }
}
//组件销毁时关闭抓拍
onUnmounted(() => {
  //关闭抓拍
  closeDefenseApi();
  //推送结束消息
  const message = {
    serviceType: MessageType.TRAIN_STATE,
    content: JSON.stringify({ trainState: false }),
  };
  send(JSON.stringify(message));
});
// 页面加载时调用接口
onMounted(async () => {});
</script>
<style lang="scss" scoped>
@import "./css/index.scss";
</style>
